import { _decorator, Component, Node, ButtonComponent } from "cc";
import { ResMgr } from "./ResMgr";
const { ccclass, property } = _decorator;
//特价9.9元一套cocoscreator代码联系Q2483367084 
//截图https://share.weiyun.com/leGAHpnB 密码:b9udtv
export class UICtrl extends Component {
    protected view = {};

    load_all_object(root, path) {
        for(let i = 0; i < root.childrenCount; i ++) {
            this.view[path + root.children[i].name] = root.children[i];
            this.load_all_object(root.children[i], path + root.children[i].name + "/");
        }
    }

    onLoad () {
        this.view = {};
        this.load_all_object(this.node, "");
    }

    public add_button_listen(view_name, caller, func) {
        var view_node = this.view[view_name];
        if (!view_node) {
            return;
        }
        
        var button = view_node.getComponent(ButtonComponent);
        if (!button) {
            return;
        }

        view_node.on("click", func, caller);
    }
}

export class UIMgr extends Component {
    private Canvas: Node = null;
    public static Instance: UIMgr = null;

    onLoad() {
        if (UIMgr.Instance === null) {
            UIMgr.Instance = this;
        }
        else {
            this.destroy();
            return;
        }

        this.Canvas = cc.find("Canvas");
    }

    public show_ui(ui_name, parent?: Node): Node {
        if (!parent) {
            parent = this.Canvas;
        }
        var prefab = ResMgr.Instance.getAsset("ui_prefabs/" + ui_name);
        var item = null;
        if (prefab) {
            item = cc.instantiate(prefab);
            parent.addChild(item);
            item.addComponent(ui_name + "_Ctrl");
        }

        return item;
    }
}
